package com.fuhan.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.fuhan.common.exception.CodeException;
import com.fuhan.common.exception.UserActionException;
import com.fuhan.common.restful.ResponseEnum;
import com.fuhan.config.TokenConfig;
import com.fuhan.mapper.UserMapper;
import com.fuhan.pojo.User;
import com.fuhan.utils.common.CreateRandomString;
import com.fuhan.utils.redis.RedisTool;
import com.fuhan.utils.token.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Chao
 * @description:
 * @Date: 2021/1/28 14:42
 */
@Service
public class UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private RedisTool redis;

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     *
     * @param username 账号
     * @param password 密码
     * @return 包含用户信息和token认证的map
     */
    public Map<String, Object> login(String username, String password, String identify, String code) {
        User user = userMapper.getUser(username,password);
        String code1 = (String) redis.get(identify);
        System.out.println("redis中的验证码" + code1);
        if (!code1.equals(code)){
            // 验证码错误
            LOGGER.debug("输入了错误的验证码={},正确的验证码={}",code,code1);
            throw new CodeException("验证码错误",ResponseEnum.CODE_ERROR);
        }
        //System.out.println(user);
        if (!(user != null)){
            LOGGER.debug("输入了不匹配的账号密码，username={},password={}",username,password);
            // 如果没有找到用户或者用户账号密码不匹配
            throw new UserActionException("账号密码不匹配", ResponseEnum.NOT_MATCH);
        }
        // 清空密码信息
        user.setPassword(null);

        // 生成token
        String token = TokenUtil.createJWT(user.getId(), TokenConfig.TOKEN_TTL);
        // 将token和用户信息保存在
        redis.setHash(token,"value",user.getId(),TokenConfig.TOKEN_TTL);
        redis.expire(token,TokenConfig.TOKEN_TTL);
        LOGGER.debug("将token和用户信息保存到redis中,key={},ttl={}", token, TokenConfig.TOKEN_TTL);
        Map<String,Object> result = new HashMap<>();
        result.put("userInfo",user);
        result.put("token",token);
        LOGGER.debug("返回登录信息,result={}", result);
        return  result;
    }


    /**
     * 验证码
     *
     * @return 验证码的base64加密字符串
     */
    public Map<String,String> getVerificationCode(){
        // 生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);

        // 获取验证码对应字符
        String code = lineCaptcha.getCode();

        // 获取验证码base64加密的图像
        String imageBase64 = lineCaptcha.getImageBase64();
        //System.out.println(imageBase64);

        // 随机生成字符串，标识验证码
        String identify = CreateRandomString.getRandomString(10);
        System.out.println("随机生成字符串" + identify);
        LOGGER.debug("随机生成字符串和验证码，identify={},code={}",identify,code);

        // 将验证码和识别码添加进redis
        redis.set(identify,code,60000*10);

        Map<String,String> result = new HashMap<>();
        result.put("identify",identify);
        result.put("code",imageBase64);
        return result;
    }


}
